var draoList = {}; //存储 下拉列表显示的值
///////////////////////////////////////
//产生唯一的设备id从0开始
///////////////////////////////////////
window.eqp_id = [];
window.eqpPrefix = "eqp_";
window.measurePrefix = "measure_";
// window.appendEqpId = function(val) {
// 	window.eqp_id.push(val);
// 	console.dir(window.eqp_id);
// }
// //获取唯一的设备id
// window.getEqpId = function() {

// 	var basicAddr = 1000;
// 	var find = false;
// 	var length = window.eqp_id.length;
// 	for (var j = 0; j < length; j++) {
// 		var val = basicAddr + j;
// 		if (window.eqp_id[j] != val) {
// 			window.eqp_id.splice(j, 0, val);
// 			console.dir("insert :" + val + "result:" + window.eqp_id);
// 			return val;
// 			//find = true;
// 		}
// 	}
// 	if (find == false) {
// 		var val=length + basicAddr
// 		window.eqp_id.splice(length, 1, val);
// 		console.dir("append aaa:" + val + "result:" + window.eqp_id);
// 		console.warn("aaaaaaaaaaaaa"+val);
// 		return val;
// 	}


// }
// //删除一个数据，或是删除一个子数组。
// window.removeEqpId = function(val) {
// 	var length = window.eqp_id.length;
// 	console.dir("delete :" + val);
// 	for (var i = 0; i < length; i++) {
// 		if (window.eqp_id[i] == val) {
// 			window.eqp_id.splice(i, 1);
// 			console.dir("delete :" + val + " result:" + window.eqp_id);
// 		}
// 	}
// }
// 0    系统         SystemParam
// 1    顶层母线     TopBusParam
// 2    变压器       TransFormerParam
// 3    非顶层母线   NoTopBusParam
// 4    集电线       SetWire
// 5    无功补偿装置 SvgParam 
// 6    电容器       CapParam
// 7    风机机组     FansParam 
// 8    光伏逆变器   PV
// 9    分段开关     Bresker
// 10   集群         ClusterParam
/*设备序号对应的*/
var typeToname = [
	"System",
	"TopBus",
	"TransFormer",
	"NoTopBus",
	"SetWire",
	"Svg",
	"Cap",
	"Fans",
	"PVI",
	"Bresker",
	"Cluster"
];

//页面之间的参数传递
var gPageParam = {

	processPage: {},
	configPage: {
		gens: [],
		gensName: []
	},
	eqpType: "",
	driverProcName: ""
}

function testEqpId() {
	//$.config.Eqp.append(1);

	// appendEqpId(3);
	// appendEqpId(4);
	// console.dir(window.getEqpId());
	// window.removeEqpId(4);
	// console.dir(window.getEqpId());
	// console.dir(window.getEqpId());
	// console.dir(window.getEqpId());
	// console.dir(window.getEqpId());
	// console.dir(window.getEqpId());
	// window.removeEqpId(4);
	// console.dir(window.getEqpId());
	// console.dir(window.getEqpId());
	// console.dir(window.getEqpId());
	// window.removeEqpId(5);
	// console.dir(window.getEqpId());
	// console.dir(window.getEqpId());
}
//========================================================================
// 扩展实现 ajax返回提示。
//

$.config = {
	//定义设备枚举，设备树判断的时候会用到
	eqpEnum: {
		"System": 0,
		"TopBus": 1,
		"TransFormer": 2,
		"NoTopBus": 3,
		"SetWire": 4,
		"Svg": 5,
		"Cap": 6,
		"Fans": 7,
		"PV": 8,
		"Bresker": 9,
		"Cluster": 10
	}, //FAN 风机 pvi photovoltiac inverter 光伏逆变器
	//设备在html页面的ID前缀
	eqpPrefix: "eqp_",
	//量测ID在表格field中的前缀
	measurePrefix: "measure_",
	//格式化，0~1440的整数为是时间格式
	TimeFromInt: function(value) {
		var hour = parseInt(value / 60);
		var hourstr = hour < 10 ? "0" + hour : hour;
		var mi = parseInt(value % 60);
		var mistr = mi < 10 ? "0" + mi : mi;
		text = hourstr + ':' + mistr;
		return text;
	},
	//产生设备号，不重复的 从1000，开始的
	EqpId: (function() {
		///////////////////////////////////////
		window.eqp_id = [];

		appendEqpId = function(val) {
			window.eqp_id.push(val);
			console.dir(window.eqp_id);
		}
		//获取唯一的设备id
		getEqpId = function() {

			var basicAddr = 1000;
			var find = false;
			var length = eqp_id.length;
			for (var j = 0; j < length; j++) {
				var val = basicAddr + j;
				if (window.eqp_id[j] != val) {
					window.eqp_id.splice(j, 0, val);
					console.dir("insert :" + val + "result:" + eqp_id);
					return val;
					find = true;
				}
			}
			if (find == false) {
				var val = length + basicAddr
				eqp_id.splice(length, 1, val);
				console.dir("append :" + val + "result:" + eqp_id);
				return val;
			}


		}
		//删除一个数据，或是删除一个子数组。
		removeEqpId = function(val) {
			var length = eqp_id.length;
			console.dir("delete :" + val);
			for (var i = 0; i < length; i++) {
				if (eqp_id[i] == val) {
					eqp_id.splice(i, 1);
					console.dir("delete :" + val + " result:" + eqp_id);
				}
			}
		}
		return {
			get: getEqpId,
			remove: removeEqpId,
			append: appendEqpId

		}
	}()),

	postData: function(url, data, callBack) {
		$.ajax({
			type: "post",
			url: url,
			data: data,
			dataType: "json",
			complete: function() {
				console.dir("加载当前机组配置完成！");
			},
			success: function(data) {
				$.config.ajaxMsg(data);

				//只在成功操作的时候调用回调函数。
				if (data.statusCode == 200) {
					callBack(true);

				} else {
					//callBack(true);
				}

			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				//callBack(false);
				console.warn("加载机组配置数据失败！" + errorThrown);
			}
		});
	},
	// ==========================================================================
	// {
	// 	"statusCode": "200",
	// 	"message": "操作成功",
	// 	"navTabId": "",
	// 	"rel": "",
	// 	"callbackType": "closeCurrent",
	// 	"forwardUrl": "
	// }

	ajaxMsg: function(msg_data) {
		//确保dom结构只添加一次
		var toolTip = $("#ajaxMsg");
		if (toolTip[0]) {} else {

			toolTip = $('<div   id="ajaxMsg" value="Hover over me to see the tooltip" ></div>').appendTo('body');
			toolTip.jqxTooltip({
				position: 'absolute', //'absolute' 
				theme: theme,
				content: 'This is a jqxButton.',
				top: 0,
				width: 200,
				height: 100,
				showArrow: true,
				showDelay: 1000, //设置显示时间
				trigger: 'click' //点击的时候才显示
			});
		}

		function ajaxResultMsg(data) {
			if (toolTip[0]) {
				var img = 'Warning.png'; //Complete.png;
				//alert(data.statusCode);
				if (data.statusCode) {
					switch (parseInt(data.statusCode)) {
						case 200:
							{
								img = 'Complete.png';

							}
							break;
						case 300:
							{
								img = 'Warning.png';

							}
							break;
						case 301:
							{
								img = 'Warning.png';

							};
						default:
							{}
					}
				}

				var msg = '<img style="float:left;height:40px;width:40px"  src="../images/' + img + '" />';
				var text = data.message;
				if (text)
					msg += '<div style="float:left">' + text + '</div>';
				else if (data)
					msg += '<div style="float:left">' + data + '</div>';
				else
					msg += '<div style="float:left">未知错误</div>';
				toolTip.jqxTooltip({
					absolutePositionX: $(window).width() / 2 - 100, //显示在屏幕中间
					content: msg
				});
				toolTip.jqxTooltip('open');


			} else {
				console.warn("创建toolTip失败！当前提示消息：" + data);
			}
		}
		ajaxResultMsg(msg_data);
		// return {
		// 	showMsg: ajaxResultMsg
		// };
	},
	alertDlg: function(msg_data) {
		//确保dom结构只添加一次
		var dlg = $("#alertDlg");
		if (dlg[0]) {} else {

			dlg = $('<div   id="alertDlg"   ><div></div><div>   <p id="altmsg"></p><div style="position:absolute;bottom:30px;padding:5px;width:100%;"><input  style="margin-left:60px" type="button" value="确定" id="alt_ok" /></div>           </div></div>').appendTo('body');
			dlg.jqxWindow({
				title: '提示', //'absolute' 
				theme: theme,
				resizable: false,
				isModal: true,
				cancelButton: $('#alt_ok'),
				height: 150,
				width: 200,
				initContent: function() {
					$('#alt_ok').jqxButton({
						theme: theme,
						width: '65px'
					});
				}
			});
		}

		function alertMsg(msg) {
			if (dlg[0]) {
				dlg.find('#altmsg').html(msg);
				//dlg.showmsg(msg);

				dlg.jqxWindow('open');


			} else {
				console.warn("创建alertDlg失败！当前提示消息：" + msg);
			}
		}
		alertMsg(msg_data);
	},
	prompt: function(callBack, msg) {
		//确保dom结构只添加一次
		var _call = function() {
			alert("_call")
		}
		var dlg = $("#promptdlg");
		if (dlg[0]) {} else {

			dlg = $('<div id="promptdlg"><div > 提示输入</div><div ><div style="width:200px;height:80px"><div  id="prompt_msg" style="float:left" > 请输入：</div><input  type="text" id="promt_val"/></div><div style="width:200px;height:30px; background-color:#131313; "><div style="width:200px;height:30px;margin:0 auto;"><div id="prompt_ok" style="float:left" >确认</div><div id="prompt_cancel"style="float:right" >取消</div></div></div></div></div>').appendTo('body');
			dlg.jqxWindow({
				title: '提示', //'absolute' 
				theme: theme,
				//resizable: false,
				isModal: true,
				cancelButton: $('#prompt_cancel'),
				okButton: $('#prompt_ok'),
				// height: 150,
				// width: 220,
				modalZIndex: 999999,
				zIndex: 999999,
				initContent: function() {
					$('#prompt_ok,#prompt_cancel').jqxButton({
						theme: theme,
						width: '65px',
						height: 25
					});
					$('#promt_val').jqxInput({
						theme: theme,
						width: '100px',
						height: 25
					});
				}
			});

		}

		function exc(callBack) {
			if (callBack)
				_call = callBack;
			$('#prompt_msg').html(msg);
			dlg.jqxWindow('open');
			//清空输入框的数据。
			$('#promt_val').jqxInput("val", "");
			$('#promptdlg #prompt_ok').one("click", function(event) {
				// 获取当前的tree中的设备的select项的数据，返回并添加到驱动数据列表中，供参数配置

				dlg.value = $('#promt_val').jqxInput("val");
				dlg.jqxWindow('close');
				_call(dlg);
			});
		}
		exc(callBack);

	},

	modalDlg: function(htmlbody, callBack) {
		//确保dom结构只添加一次
		var _call = function() {
			alert("_call")
		}
		var dlg = $("#modalDlg");
		if (dlg[0]) {} else {

			dlg = $('<div id="modalDlg"><div>     提示输入</div><div > <div id="dlg_content"></div>  <div style="width:200px;height:30px; background-color:#131313; "><div style="width:200px;height:30px;margin:0 auto;"><div id="prompt_ok" style="float:left">       确认</div><div id="prompt_cancel" style="float:right">       取消</div></div></div></div></div>').appendTo('body');
			dlg.jqxWindow({
				title: '提示', //'absolute' 
				theme: theme,
				//resizable: false,
				isModal: true,
				cancelButton: $('#prompt_cancel'),
				okButton: $('#prompt_ok'),
				  height: 150,
				  width: 220,
				modalZIndex: 999999,
				zIndex: 999999,
				initContent: function() {
					$('#prompt_ok,#prompt_cancel').jqxButton({
						theme: theme,
						width: '65px',
						height: 25
					});
				 
				}
			});

		}

		function exc(callBack) {
			if (callBack)
				_call = callBack;
			//$('#dlg_content').html(msg);
			$('#dlg_content').replaceWith(htmlbody);
			dlg.jqxWindow('open');
			//清空输入框的数据。
	 
			$('#modalDlg #prompt_ok').one("click", function(event) {
				// 获取当前的tree中的设备的select项的数据，返回并添加到驱动数据列表中，供参数配置

				 
				dlg.jqxWindow('close');
				_call(dlg);
			});
		}
		exc(callBack);

	}
};


$(function($) {


	//========================
	$("#comit").off().on("click", function() {
		$.config.prompt(function(dlg) {
			alert(dlg.value);
		})
		$.config.alertDlg(msg_data);
		alert("leftnamv");
	});
	$("#export").off().on("click", function() {
		alert("leftnamv");
	});
	//窗体左上角导出 按钮等	
	$(".header_btn").jqxButton({
		width: 100,
		height: 30,
		theme: theme
	});

	//	        $(document).ready(function () {
	var leftToolBar = $("#lefgToolBar").jqxNavigationBar({
		width: 200,
		height: 682,
		theme: theme,
		expandedIndexes: ['0'],
		initContent: function(index) {
			//alert(index);
			switch (index) {
				case 0: //元件库
					{
						initComponentList("#component_list");
						return "Component";
					}
				case 1: //系统规约库
					{
						return "Drivers";
					}
				case 2: //系统参数
					{
						return "Struts";
					}
				case 3: //系统结构
					{
						initEqpTree("#struts_tree");
						$("#context_menu").load("treemenu.html", function() {
							initContextMenu("#struts_tree"); //加载完成页面，初始化tree菜单
						});
						return "Measure";
					}
				case 4: //系统集群    
					{
						initCluster("#cluster_tree");
						return "User";
					}
				case 5: //母线关系
					{


						return "Measure";
					}
				case 6: //系统进程 
					{

						initProcessTree("#process_tree");
						return "Measure";
					}
				case 7: //系统数据
					{
						initProcessDriver("#process_driver");

						return "Measure";
					}
				case 8: //系统对时
					{

						return "Measure";
					}
				case 9: //用户管理  
					{


						return "Measure";
					}

			}

		}

	});
	// Focus jqxNavigationBar.
	// $("#lefgToolBar").jqxNavigationBar('focus');
	//无法 获取item中的其他数据，或是自定义数据，只能通过index进行判断
	var getName = function(index) {
		switch (index) {
			case 0: //元件库
				{
					$("#dlg_body").load("component_base.html");
					return "Component";
				}
			case 1: //系统规约库
				{
					return "Drivers";
				}
			case 2: //系统参数
				{
					$("#dlg_body").load("sysProperty.html");
					return "Struts";
				}
			case 3: //系统结构
				{

					return "Measure";
				}
			case 4: //系统集群    
				{
					$("#dlg_body").load("component_cluster.html");
					return "User";
				}
			case 5: //母线关系
				{


					return "Measure";
				}
			case 6: //系统进程 
				{
					$("#dlg_body").load("system_drivers.html");

					return "Measure";
				}
			case 7: //系统数据
				{
					//$("#dlg_body").load("driverMeasure.html");

					return "Measure";
				}
			case 8: //系统对时
				{

					return "Measure";
				}
			case 9: //用户管理  
				{


					return "Measure";
				}

		}
	}
	leftToolBar.bind('expandedItem', function(event) {
		//var aaa=$(event.target);
		//alert(aaa.html());//.attr("item_val"));
		var text = getName(event.item);
		//  alert(event.item);
		//      $('#Events').jqxPanel('prepend', '<div style="margin-top: 5px;">Expanded: ' + text + '</div>');

	});


});
/////////////////////////////////////////////////////////////
//          系统结构
//
/////////////////////////////////////////////////////////////

function initEqpTree(treewidget) {
	//绑定 添加设备树需要的计数id到tree
	var equdata = {};
	equdata["newid"] = 0;
	// equdata["PhyscPid"] = 0;
	// equdata["LogicPid"] = 0;
	// equdata["EqptType"] = 1;

	$(treewidget).data("equ", equdata);
	// prepare the data
	var source = {
		dataType: "csv",
		datafields: [{
			name: 'EqptId',
			type: "number"
		}, {
			name: 'PhyscPid',
			type: "number"
		}, {
			name: 'EqptName',
			type: "string"
		}, {
			name: 'EqptType',
			type: "string"
		}, {
			name: 'LogicPid',
			type: "number"
		}, {
			name: 'IsLogic',
			type: "number"
		}],
		id: 'EqptId',
		// localdata: treeData,
		url: 'defaultData/eqptree.csv',

		hierarchy: {
			keyDataField: {
				name: 'EqptId'
			},
			parentDataField: {
				name: 'PhyscPid'
			}
		},
		addRow: function(rowID, rowData, position, parentID, commit) {
			// synchronize with the server - send insert command
			// call commit with parameter true if the synchronization with the server is successful 
			// and with parameter false if the synchronization failed.
			// you can pass additional argument to the commit callback which represents the new ID if it is generated from a DB.
			commit(true);
			$(treewidget).data("equ")["newid"] = rowID;
			// $(treewidget).data("equ")["EqptId"] = rowID;
		},
		updateRow: function(rowID, rowData, commit) {
			// synchronize with the server - send update command
			// call commit with parameter true if the synchronization with the server is successful 
			// and with parameter false if the synchronization failed.
			$(treewidget).data("equ")["newid"] = rowID;
			commit(true);
		},
		deleteRow: function(rowID, commit) {
			// synchronize with the server - send delete command
			// call commit with parameter true if the synchronization with the server is successful 
			// and with parameter false if the synchronization failed.
			// alert(rowID);//删除id，需要删除当前id和以当前id作为parent的所有项，该部分在服务端做。
			$(treewidget).data("equ")["newid"] = rowID;
			commit(true);
		}


	};

	// create data adapter.
	var dataAdapter = new $.jqx.dataAdapter(source, {
		async: false
	});
	// perform Data Binding.
	// dataAdapter.dataBind();
	// get the tree items. The first parameter is the item's id. The second parameter is the parent item's id. The 'items' parameter represents 
	// the sub items collection name. Each jqxTree item has a 'label' property, but in the JSON data, we have a 'text' field. The last parameter 
	// specifies the mapping between the 'text' and 'label' fields.  
	var records = dataAdapter.getRecordsHierarchy('id', 'parentid', 'items', [{
		name: 'text',
		map: 'label'
	}]);
	//Invoke the removeFilter method of the jqxTreeGrid.
	//$(treewidget).jqxTreeGrid('scrollOffset', 10, 10);
	$(treewidget).jqxTreeGrid({
		source: source,
		altrows: true,
		height: '500',
		width: 200,
		showheader: false,

		theme: theme,
		ready: function() { // 加载完成了统计所有rows

			var rows = $(treewidget).jqxTreeGrid('getRows');
			var count = 0;

			var traverseTree = function(rows) {
				for (var i = 0; i < rows.length; i++) {
					count++;
					$.config.EqpId.append(rows[i].EqptId);
					//.dir(rows[i].EqptId+"===============");
					//rowsData += rows[i].FirstName + " " + rows[i].LastName + "\n";
					if (rows[i].records) {
              
						traverseTree(rows[i].records);
					}
				}
			};
			traverseTree(rows);

			$(treewidget).data("equ")["EqptId"] = count;
		},
		columns: [{
			text: '设备名称',
			dataField: "EqptName",
			align: 'center',
			width: '100%',
			cellsRenderer: function(row, column, value, rowData) {
			//	console.dir(rowData.EqptName + '[' + rowData.EqptId + '|' + rowData.PhyscPid + '|' + rowData.LogicPid + '|' + rowData.IsLogic + ']');
				return rowData.EqptName + '[' + rowData.EqptId + '|' + rowData.LogicPid + ']';
			}
		}]

	}); //end treegrid

	//$("#lefgToolBar").jqxTree( {height: '679px', width: '200px' ,theme:theme});
	$(treewidget).css('visibility', 'visible');
	// create context menu


	//  $(treewidget).on('contextmenu', function () {
	//      return false;
	//   });
	//   $(treewidget).jqxTreeGrid('addRow', null, {EqptName:"aaaaaaaa",EqptId:999,EqptType:3,LogicPid:89}, 'last', 9999);
	//$(treewidget).jqxTreeGrid('addRow', null, {});	


	$(treewidget).on('rowClick', function(event) {
		//alert("row");
		//顶层节点，不能删除，只有底层节点才能删除
		// event args.

		var args = event.args;
		// row data.
		var row = args.row;
		// row key.
		var key = args.key;
		// original click event.
		var clickEvent = args.originalEvent;
		//========================在row上点击的事件，将不会再treewidget的ckick事件中处理
		if (clickEvent && clickEvent.stopPropagation) {
			//W3C取消冒泡事件
			clickEvent.stopPropagation();
		} else {
			//IE取消冒泡事件
			clickEvent.cancelBubble = true;
		}

		//  var selection = $(treewidget).jqxTreeGrid('getSelection');
		//		alert(row );

		if (args.originalEvent.button == 2) {

			var scrollTop = $(window).scrollTop();
			var scrollLeft = $(window).scrollLeft();
			//alert( parseInt(event.args.originalEvent.clientY) + 5 + parseInt(scrollTop));
			//   $("#context_menu").jqxMenu('open', 20, 20);  
			var propertyType = $(treewidget).jqxTreeGrid('getCellValue', key, 'EqptType');
		 
			$(".treeMenu").jqxMenu('close');
			// alert(typename[propertyType]);


			$("#component_" + typeToname[propertyType] + "_menu").jqxMenu('open', parseInt(event.args.originalEvent.clientX) + 5 + scrollLeft, parseInt(event.args.originalEvent.clientY) + 5 + scrollTop);

			return false;
		} else {


		}
	});
	$(treewidget).on('bindingComplete', function(event) {


		// Some code here. 
	});
	//=============双击实现对设备详情的编辑
	$(treewidget).on('rowDoubleClick', function(event) {
		//alert("row");
		//顶层节点，不能删除，只有底层节点才能删除


		var args = event.args;
		//只响应 左键双机
		if (args.originalEvent.button != 0) {

			return;
		}
		// row data.
		var row = args.row;
		// row key.
		var key = args.key;
		//获取当前选择的grid  select-measure字段的值
		var text = $(treewidget).jqxTreeGrid('getCellValue', key, 'EqptName');
		var value = $(treewidget).jqxTreeGrid('getCellValue', key, 'EqptType');
		//value作为子界面请求
		if (value && value.indexOf("NaN") < 0) {
			gPageParam.eqpType = typeToname[value];
			//机组一下的设备没有数据编辑页面，所以需要在这里判断
			if (typeToname[value]) {
				$("#dlg_body").load("component_" + typeToname[value] + ".html" + "?" + Date.parse(new Date()));
			}
		}

	});



}
////////////////////////////////////////////
//       系统量测
//
//所有驱动程序的树形列表。processID， processName ,本页显示
//                        driverName 驱动配置页面，需要根据不同的驱动加载不同的页面
////////////////////////////////////////////
function initProcessDriver(treewidget) {
	//绑定 添加设备树需要的计数id到tree

	// prepare the data
	var source = {
		dataType: "csv",
		datafields: [{
			name: 'processID',
			type: "number"
		}, {
			name: 'processName',
			type: "string"
		}, {
			name: 'driverName',
			type: "string"
		}],
		id: 'processID',
		// localdata: treeData,
		url: 'defaultData/SystemProcess_driver.csv',

		hierarchy: {
			keyDataField: {
				name: 'processID'
			}
		}


	};

	// create data adapter.
	var dataAdapter = new $.jqx.dataAdapter(source, {
		async: false
	});
	// perform Data Binding.
	// dataAdapter.dataBind();
	// get the tree items. The first parameter is the item's id. The second parameter is the parent item's id. The 'items' parameter represents 
	// the sub items collection name. Each jqxTree item has a 'label' property, but in the JSON data, we have a 'text' field. The last parameter 
	// specifies the mapping between the 'text' and 'label' fields.  
	var records = dataAdapter.getRecordsHierarchy('id', 'processID', 'items', [{
		name: 'text',
		map: 'label'
	}]);
	//Invoke the removeFilter method of the jqxTreeGrid.
	//$(treewidget).jqxTreeGrid('scrollOffset', 10, 10);
	$(treewidget).jqxTreeGrid({
		source: source,
		altrows: true,
		height: '500',
		width: '100%',
		showheader: false,

		theme: theme,
		ready: function() { // 加载完成了统计所有rows


		},
		columns: [{
				text: '设备名称',
				dataField: "processName",
				align: 'center',
				width: '100%',
				cellsRenderer: function(row, column, value, rowData) {

					return rowData.processName;
				}
			}
			/*,
                  { text: 'Population', dataField: "value", align: 'right', cellsAlign: 'right', width: '50%' }*/
		]

	}); //end treegrid

	//$("#lefgToolBar").jqxTree( {height: '679px', width: '200px' ,theme:theme});
	$(treewidget).css('visibility', 'visible');


	$(treewidget).on('bindingComplete', function(event) {


		// Some code here. 
	});
	//=============双击实现对设备详情的编辑
	$(treewidget).on('rowDoubleClick', function(event) {
		//alert("row");
		//顶层节点，不能删除，只有底层节点才能删除


		var args = event.args;
		// row data.
		var row = args.row;
		// row key.
		var key = args.key;
		//获取当前选择的grid  select-measure字段的值
		gPageParam.processPage.processName = $(treewidget).jqxTreeGrid('getCellValue', key, 'processName');
		gPageParam.processPage.driverName = $(treewidget).jqxTreeGrid('getCellValue', key, 'driverName');

		// $("#dlg_body").html(text+"====="+value);
		$("#dlg_body").load("driverMeasure.html");

	});

}

////////////////////////////////////////////
//       系统集群
//系统素有集群列表，eqpid 集群的设备编号，eqpname 集群的名称
////////////////////////////////////////////
function initCluster(treewidget) {
	//绑定 添加设备树需要的计数id到tree

	// prepare the data
	var source = {
		dataType: "csv",
		datafields: [{
			name: 'EqpId',
			type: "number"
		}, {
			name: 'EqpName',
			type: "string"
		}],
		id: 'EqpId',
		// localdata: treeData,
		url: 'defaultData/component/cluster.csv',

		hierarchy: {
			keyDataField: {
				name: 'EqpId'
			}
		}
	};

	// create data adapter.
	var dataAdapter = new $.jqx.dataAdapter(source, {
		async: false
	});
	// perform Data Binding.
	// dataAdapter.dataBind();
	// get the tree items. The first parameter is the item's id. The second parameter is the parent item's id. The 'items' parameter represents 
	// the sub items collection name. Each jqxTree item has a 'label' property, but in the JSON data, we have a 'text' field. The last parameter 
	// specifies the mapping between the 'text' and 'label' fields.  
	var records = dataAdapter.getRecordsHierarchy('id', 'processID', 'items', [{
		name: 'text',
		map: 'label'
	}]);
	//Invoke the removeFilter method of the jqxTreeGrid.
	//$(treewidget).jqxTreeGrid('scrollOffset', 10, 10);
	$(treewidget).jqxTreeGrid({
		source: source,
		altrows: true,
		height: '500',
		width: '100%',
		showheader: false,

		theme: theme,
		ready: function() { // 加载完成了统计所有rows


		},
		columns: [{
				text: '设备名称',
				dataField: "EqpName",
				align: 'center',
				width: '100%',
				cellsRenderer: function(row, column, value, rowData) {

					return rowData.EqpName;
				}
			}
			/*,
                  { text: 'Population', dataField: "value", align: 'right', cellsAlign: 'right', width: '50%' }*/
		]

	}); //end treegrid

	//$("#lefgToolBar").jqxTree( {height: '679px', width: '200px' ,theme:theme});
	$(treewidget).css('visibility', 'visible');


	$(treewidget).on('bindingComplete', function(event) {


		// Some code here. 
	});
	//=============双击实现对设备详情的编辑
	$(treewidget).on('rowDoubleClick', function(event) {
		//alert("row");
		//顶层节点，不能删除，只有底层节点才能删除


		var args = event.args;
		// row data.
		var row = args.row;
		// row key.
		var key = args.key;
		//获取当前选择的grid  select-measure字段的值
		gPageParam.processPage.EqpId = $(treewidget).jqxTreeGrid('getCellValue', key, 'EqpId');
		gPageParam.processPage.EqpName = $(treewidget).jqxTreeGrid('getCellValue', key, 'EqpName');
		gPageParam.eqpType = "cluster";
		// alert(	gPageParam.processPage.EqpName );
		// $("#dlg_body").html(text+"====="+value);
		$("#dlg_body").load("component_cluster_measure.html");
	});

}
////////////////////////////////////////////
//        系统元件
// 系统所有元件列表，eqpid 系统设备库的ID，eqpname 系统设备哭的名称
////////////////////////////////////////////
function initComponentList(treewidget) {
	//绑定 添加设备树需要的计数id到tree

	// prepare the data
	var source = {
		dataType: "csv",
		datafields: [{
			name: 'EqpId',
			type: "number"
		}, {
			name: 'EqpName',
			type: "string"
		}],
		id: 'EqpId',
		// localdata: treeData,
		url: 'defaultData/component/list.csv',

		hierarchy: {
			keyDataField: {
				name: 'EqpId'
			}
		}
	};

	// create data adapter.
	var dataAdapter = new $.jqx.dataAdapter(source, {
		async: false
	});
	// perform Data Binding.
	// dataAdapter.dataBind();
	// get the tree items. The first parameter is the item's id. The second parameter is the parent item's id. The 'items' parameter represents 
	// the sub items collection name. Each jqxTree item has a 'label' property, but in the JSON data, we have a 'text' field. The last parameter 
	// specifies the mapping between the 'text' and 'label' fields.  
	var records = dataAdapter.getRecordsHierarchy('id', 'processID', 'items', [{
		name: 'text',
		map: 'label'
	}]);
	//Invoke the removeFilter method of the jqxTreeGrid.
	//$(treewidget).jqxTreeGrid('scrollOffset', 10, 10);
	$(treewidget).jqxTreeGrid({
		source: source,
		altrows: true,
		height: '500',
		width: '100%',
		showheader: false,

		theme: theme,
		ready: function() { // 加载完成了统计所有rows


		},
		columns: [{
				text: '设备名称',
				dataField: "EqpName",
				align: 'center',
				width: '100%',
				cellsRenderer: function(row, column, value, rowData) {

					return rowData.EqpName;
				}
			}
			/*,
                  { text: 'Population', dataField: "value", align: 'right', cellsAlign: 'right', width: '50%' }*/
		]

	}); //end treegrid

	//$("#lefgToolBar").jqxTree( {height: '679px', width: '200px' ,theme:theme});
	$(treewidget).css('visibility', 'visible');


	$(treewidget).on('bindingComplete', function(event) {


		// Some code here. 
	});
	//=============双击实现对设备详情的编辑
	$(treewidget).on('rowDoubleClick', function(event) {
		//alert("row");
		//顶层节点，不能删除，只有底层节点才能删除


		var args = event.args;
		// row data.
		var row = args.row;
		// row key.
		var key = args.key;
		//获取当前选择的grid  select-measure字段的值
		gPageParam.processPage.EqpId = $(treewidget).jqxTreeGrid('getCellValue', key, 'EqpId');
		gPageParam.processPage.EqpName = $(treewidget).jqxTreeGrid('getCellValue', key, 'EqpName');
		gPageParam.eqpType = "cluster";
		// alert(	gPageParam.processPage.EqpName );
		// $("#dlg_body").html(text+"====="+value);
		$("#dlg_body").load("component_detail.html");
	});

}
////////////////////////////////////////////////////////////////////////
//
//返回tablesource
////////////////////////////////////////////////////////////////////////
function tableSource(url) {

	var source = {
		datatype: "xml",
		datafields: [{
			name: 'Desc',
			map: 'm\\:properties>d\\:Desc'
		}, {
			name: 'Field',
			map: 'm\\:properties>d\\:Field'
		}, {
			name: 'DefaultValue',
			map: 'm\\:properties>d\\:DefaultValue'
		}, {
			name: 'EData',
			map: 'm\\:properties>d\\:EData'
		}, {
			name: 'DataType',
			map: 'm\\:properties>d\\:DataType'
		}],
		root: "content",
		// record : "content",
		id: 'm\\:properties>d\\:Field',
		url: url
	};

	return source;
}

function getComponentList() {
	var source = {

		dataType: "csv",
		dataFields: [{
				name: "typeId",
				type: "number"
			}, // Possible values: 'string', 'date', 'number', 'float', 'int', 'bool'.
			{
				name: "typeName",
				type: "string",
				format: ""
			}, {
				name: "IsLogic",
				type: "bool"
			}, {
				name: "SVGInfo",
				type: "string"
			}, {
				name: "View",
				type: "string"
			}
		],
		url: "compoent_base.csv"
	};

	var dataAdapter = new $.jqx.dataAdapter(
		source, {
			autoBind: true,
			loadComplete: function() {
				var records = dataAdapter.records;
				var length = records.length;
				// loop through the records and display them in a table.                  
				for (var i = 0; i < length; i++) {
					var record = records[i];
					//  alert();                      
					draoList[record["typeId"]] = record["typeName"];
				}
			} /*,  uniqueDataFields: ["component_type"] */
		}
	);

	return dataAdapter;

}
////////////////////////////////////////////////////////
//             系统进程配置
//1.双机空白处或是进入系统配置项，右侧出现系统进程配置表格
//2.更改系统配置表格，同步更新右侧系统进程树，如果是通讯进程，对应的通道，规约驱动会以子节点的形式显示
//3.点击对应的进程，出现对应进程的参数配置界面。                
///////////////////////////////////////////////////////

function initProcessTree(treewidget) {

	// prepare the data
	var source = {
		dataType: "json",
		datafields: [{
			name: 'desc',
			type: "string"
		}, {
			name: 'name',
			type: "string"
		}, {
			name: "proc",
			type: "array"
		}],

		// localdata: treeData,
		url: 'defaultData/SystemProcess.json',

		hierarchy: {
			root: "proc"
		}

	};

	// create data adapter.
	var dataAdapter1 = new $.jqx.dataAdapter(source, {
		//autoBind:true,
		async: false
	});
	// perform Data Binding.
	// dataAdapter.dataBind();
	// get the tree items. The first parameter is the item's id. The second parameter is the parent item's id. The 'items' parameter represents 
	// the sub items collection name. Each jqxTree item has a 'label' property, but in the JSON data, we have a 'text' field. The last parameter 
	// specifies the mapping between the 'text' and 'label' fields.  
	//  var records = dataAdapter.getRecordsHierarchy('id', 'pProcID', 'items', [{ name: 'text', map: 'label'}]);
	//Invoke the removeFilter method of the jqxTreeGrid.
	//$(treewidget).jqxTreeGrid('scrollOffset', 10, 10);
	$(treewidget).jqxTreeGrid({
		source: source,
		altrows: dataAdapter1,
		height: '600',
		width: 200,
		showheader: false,

		theme: theme,
		ready: function() { // 加载完成了统计所有rows
			// alert(treewidget);
			$(treewidget).jqxTreeGrid('expandRow', 0);
		},
		columns: [{
				text: '设备名称',
				dataField: "desc",
				align: 'center',
				width: '100%',
				cellsRenderer: function(row, column, value, rowData) {
					if (rowData.name != "")
						return rowData.desc + "(" + rowData.name + ")";
				}
			}
			/*,
                  { text: 'Population', dataField: "value", align: 'right', cellsAlign: 'right', width: '50%' }*/
		]

	}).on('dblclick', function(event) {

		//双机空白处，出现系统进程编辑界面
		// $("#dlg_body").load("system_drivers.html");
		//alert("dbclick");
		console.dir("dblclick");

	}); //end treegrid


	$(treewidget).css('visibility', 'visible');


	//============ 双机 根据value 去查询服务端对应的精彩
	$(treewidget).on('rowDoubleClick', function(event) {
		//alert("row");
		//顶层节点，不能删除，只有底层节点才能删除


		var args = event.args;
		// row data.
		var row = args.row;
		// row key.
		var key = args.key;

		var clickEvent = args.originalEvent;
		//========================在row上点击的事件，将不会再treewidget的ckick事件中处理
		if (clickEvent && clickEvent.stopPropagation) {
			//W3C取消冒泡事件
			console.dir("rowDoubleClick");
			clickEvent.stopPropagation();
		} else {
			//IE取消冒泡事件
			alert("eeeeeeee");
			clickEvent.cancelBubble = true;
		}


		// 根据value的值 获取，服务端对应value行   
		var procDesc = $(treewidget).jqxTreeGrid('getCellValue', key, 'desc');
		var procName = $(treewidget).jqxTreeGrid('getCellValue', key, 'name');
		gPageParam.processPage = {
			"DriverType": " ",
			"ChannelType": " "
		}; //清空需要传递给下一个页面的数据
		if (procName == "") //procName 为空标识为根节点，没有任何程序
			return;
		// alert(value);//value作为子界面请求
		gPageParam.processPage.procName = procName;
		gPageParam.processPage.procDesc = procDesc;
		getConfigPage($(treewidget).jqxTreeGrid('getSelection'));

		// $("#dlg_body").load("driverProperty.html");
		// gPageParam.processPage={"DriverType":"DriverMCDT","ChannelType":"ChannelSerialPort"};
		return;
		//===================== 没有用=======================
		$.ajax({
			type: "get",
			url: "defaultData/driverType" + value + ".json",
			dataType: "json",
			complete: function() {
				alert("ok")
			}, //AJAX请求完成时隐藏loading提示
			success: function(data) {
				//判断data的中的规约类型和通道类型。根据类型加载对应的配置界面和当前配置
				/// $("input#showTime").val(data[0].demoData); 
				data;
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert(errorThrown);
			}
		});
		//=============================================

	});



}
////////////////////////////////////////////////////////////////////////////////////////
//遍历当前选择的行，获取行的child ，child包含了当前采集进程的规约和通道信息。根据规约和通道信息，加载对应的配置界面，进行配置。
//配置界面采用两个表格合并的方式进行配置，上面为通道参数，下面面为规约参数
////////////////////////////////////////////////////////////////////////////////////////
function getConfigPage(rows) {
	var row = rows[0] ? rows[0] : rows;
	var driver_row = row.records; //?rows.records: rows[0].records;
	if (driver_row) //驱动和通道在，进程的子列表里面
	{
		// alert(driver_row.length)
		//有驱动或是通道的，加载对应的配置界面，没有的就不加在
		if (driver_row.length > 0) {


			if (driver_row[0]) //驱动行
				gPageParam.processPage.DriverType = driver_row[0].name; //获取驱动exe的名称
			if (driver_row[1]) //通道行
				gPageParam.processPage.ChannelType = driver_row[1].name; //获取通道exe的名称

			gPageParam.processPage.procDesc = row.desc;
			// gPageParam.processPage.procName = row.desc;

			if (gPageParam.processPage.DriverType.indexOf("OPC") > -1) //opc的程序需要单独配置
			{
				$("#dlg_body").load("driverOPC.html");
			} else {
				$("#dlg_body").load("driverProperty.html");
			}
		} else {
			// alert(driver_row.length );

			//只有 level==1 的是进程，level==2的是 驱动通道，level==0 的是前置机 ，工作站的标识
			if (rows[0].level == 1) {
				$("#dlg_body").load("driverNone.html");
			} else {
				//console.dir("当前程序没有配置界面");
				getConfigPage(rows[0].parent);
			}
		}
	}

	//traverseTree(rows);
	//alert(rowsData);
}

function setDlgTitle(title) {
	$("#header_title #text").html(title);
}
//扩展时间格式化函数

Date.prototype.format = function(format) {
	var o = {
		"M+": this.getMonth() + 1, //month 
		"d+": this.getDate(), //day 
		"h+": this.getHours(), //hour 
		"m+": this.getMinutes(), //minute 
		"s+": this.getSeconds(), //second 
		"q+": Math.floor((this.getMonth() + 3) / 3), //quarter 
		"S": this.getMilliseconds() //millisecond 
	}

	if (/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}

	for (var k in o) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
		}
	}
	return format;
}
//返回时间的 小时*60+分钟的值 0~1440的一天的分钟的值
Date.prototype.hour_mi_int = function() {
	return this.getHours() * 60 + this.getMinutes();
}